package info.wangyuan.agent.task;


import info.wangyuan.agent.service.curd.ModelConfigService;
import info.wangyuan.agent.utils.MailUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 定时任务
 *
 * @author Albert
 * @since 2025-08-10 20:22:49
 */
@Slf4j
@Component
public class CommonTask {

    private final MailUtil mailUtil;
    private final ModelConfigService modelConfigService;

    public CommonTask(MailUtil mailUtil, ModelConfigService modelConfigService) {
        this.mailUtil = mailUtil;
        this.modelConfigService = modelConfigService;
    }

    @Value("${spring.mail.username}")
    private String fromEmail;

    @Value("${admin.email}")
    private String toEmail;

    // 每天凌晨零点检查模型健康度
    @Async
    @Scheduled(cron = "0 0 0 * * *")
    public void checkModelHealth() {
        log.info("======开始检查模型健康度======");
        modelConfigService.list().forEach(modelConfig -> {
            try {
                modelConfigService.modelTest(modelConfig);
            } catch (Exception e) {
                log.error("模型测试失败：{}", e.getMessage());
                // 发送邮件给管理员
                mailUtil.sendTextMail(fromEmail, toEmail, "模型异常", "模型 " + modelConfig.getName() + " 出现异常：" + e.getMessage());
            }
        });
        log.info("======模型健康度检查完毕======");
    }

    // 每天凌晨3点触发gc，控制 docker 容器内存
    @Scheduled(cron = "0 0 3 * * *")
    public void triggerGC() {
        Runtime runtime = Runtime.getRuntime();
        log.info("======开始触发JVM垃圾回收======");
        long beforeUsedMemory = runtime.totalMemory() - runtime.freeMemory();
        log.info("======GC前已使用内存: {} MB", beforeUsedMemory / (1024 * 1024));
        System.gc();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        long afterUsedMemory = runtime.totalMemory() - runtime.freeMemory();
        log.info("======GC后已使用内存: {} MB", afterUsedMemory / (1024 * 1024));
        log.info("======JVM垃圾回收触发完成======");
    }
}
